package com.juzi.wopu.web;

import java.io.PrintWriter;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.apache.struts2.ServletActionContext;
import com.juzi.wopu.domain.Role;
import com.juzi.wopu.query.PageList;
import com.juzi.wopu.query.RoleQuery;
import com.juzi.wopu.service.IRoleService;
import com.opensymphony.xwork2.interceptor.annotations.InputConfig;

public class RoleAction extends CRUDAaction<Role> {
	
	private static final long serialVersionUID = 1L;

	private IRoleService roleService;
	
	private Role role = new Role();
	
	private RoleQuery baseQuery = new RoleQuery();
	
	private PageList pageList;
	
	private Long[] dis;
	
	public void setRoleService(IRoleService roleService) {
		this.roleService = roleService;
	}

	@Override
	protected void list() {
		this.pageList = roleService.findByQuery(baseQuery);
	}

	@Override
	public String input() throws Exception {
		if(id!=null){
			role= roleService.get(id);
		}
		return INPUT;
	}

	public void validateSave() {
		if (StringUtils.isBlank(role.getsName())) {
			addFieldError("name", "名称不能为空");
		}
	}

	@Override
    @InputConfig(methodName="input")
	public String save() throws Exception {
		
//		if(dis != null){
//			for (Long id : dis) {
//				role.getPermissions().add(new Permission(id));
//			}
//		}
		if(id==null){
			baseQuery.setCurrentPage(Integer.MAX_VALUE);
			/*role.setDtInsert(new Date());*/
		}
		 roleService.save(role);
		return RELOAD;
	}

	@Override
	public String delete() throws Exception {
		HttpServletResponse response=ServletActionContext.getResponse();
		response.setContentType("text/json;charset=UTF-8");
		PrintWriter out = response.getWriter();
		try {
			if (id != null) {
				roleService.delete(id);
				out.print("{\"success\":true,\"msg\":\"删除成功\"}");
			}else{
				out.print("{\"success\":false,\"msg\":\"没有删除成功\"}");
			}
		} catch (Exception e) {
			e.printStackTrace();
			out.print("{\"success\":false,\"msg\":\"异常信息:"+e.getMessage()+"\"}");
		}
		return null;
	}

	@Override
	public void prepareInput() throws Exception {
		if (id != null) {
			role = roleService.get(id);
		}
	}

	@Override
	public void prepareSave() throws Exception {
		if (id == null) {
			role = new Role();
		} else {
			role = roleService.get(id);
		}
	}

	@Override
	public Role getModel() {
		return role;
	}

	public PageList getPageList() {
		return pageList;
	}

	public RoleQuery getBaseQuery() {
		return baseQuery;
	}

	public void setBaseQuery(RoleQuery baseQuery) {
		this.baseQuery = baseQuery;
	}

	public Long[] getDis() {
		return dis;
	}

	public void setDis(Long[] dis) {
		this.dis = dis;
	}
}
